<template>
  <div class="callAnalysisNew-TabSingle">
    <el-table-form ref="form" :model="query">
      <el-form-item label="统计日期:" prop="date" :table-form-merge="2">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :picker-options="pickerOptions"
          :clearable="false"
        />
      </el-form-item>

      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="getData">查询</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData"
      custom-column
      :max-height="300"
    />
    <div v-if="isShowCharts" class="chart-body">
      <Charts :options="option" />
    </div>
  </div>
</template>

<script>
  import Charts from '@/components/Charts'
  import { callAnalysisNewSingleData } from '@/api'
  import dayjs from 'dayjs'
  export default {
    components: {
      Charts
    },
    data() {
      return {
        query: {
          date: [new Date(), new Date()]
        },
        numOptions: [],
        tableData: [],
        option: {}
      }
    },
    computed: {
      pickerOptions() {
        return {
          shortcuts: [
            {
              text: '今天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近7天',
              onClick(picker) {
                const end = new Date()
                let start = new Date()
                start = dayjs().subtract(7, 'day').toDate()
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近30天',
              onClick(picker) {
                const end = new Date()
                let start = new Date()
                start = dayjs().subtract(30, 'day').toDate()
                picker.$emit('pick', [start, end])
              }
            }
          ]
        }
      },
      column() {
        return [
          {
            label: '话务员',
            prop: 'userName',
            align: 'center'
          },
          {
            label: '基础数据统计',
            prop: 'statistics1',
            align: 'center',
            children: [
              {
                label: '坐席在线时长(h)',
                prop: 'lineTimeSpan',
                align: 'center',
                width: 130,
                render: (h, { row, $index }) => (
                <span>{(row.lineTimeSpan / 3600).toFixed(2)}</span>
              )
              },
              {
                label: '离席次数',
                prop: 'unLineCount',
                align: 'center',
                width: 100
              },
              // {
              //   label: "实际工作率",
              //   prop: "workRate",
              //   align: "center",
              //   width: 100,
              //   rowspan: 2,
              //   // formatter: _this.formatter.workRateFormatter,
              //   hidden: true,
              // },
              {
                label: '接听总次数',
                prop: 'answerCount',
                align: 'center',
                width: 120,
                children: [
                  {
                    label: '新客户',
                    prop: 'answerCountNew',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.answerCountNew)}</span>
                  )
                  },
                  {
                    label: '老客户',
                    prop: 'answerCountOld',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.answerCountOld)}</span>
                  )
                  },
                  {
                    label: '合计',
                    prop: 'answerCountTotal',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.answerCountTotal)}</span>
                  )
                  }
                ]
              },
              {
                label: '接听总时长(s)',
                prop: 'answerTimeSpan',
                align: 'center',
                width: 120,
                children: [
                  {
                    label: '新客户',
                    prop: 'answerTimeSpanNew',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.answerTimeSpanNew)}</span>
                  )
                  },
                  {
                    label: '老客户',
                    prop: 'answerTimeSpanOld',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.answerTimeSpanOld)}</span>
                  )
                  },
                  {
                    label: '合计',
                    prop: 'answerTimeSpanTotal',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.answerTimeSpanTotal)}</span>
                  )
                  }
                ]
              },
              {
                label: '平均接听时长(s)',
                prop: 'answerTimeSpan',
                align: 'center',
                width: 120,
                children: [
                  {
                    label: '新客户',
                    prop: 'averageTimeSpanNew',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>
                      {row.answerCountNew > 0 &&
                        (row.answerTimeSpanNew / row.answerCountNew).toFixed(2)}
                    </span>
                  )
                  },
                  {
                    label: '老客户',
                    prop: 'averageTimeSpanOld',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>
                      {row.answerCountOld > 0 &&
                        (row.answerTimeSpanOld / row.answerCountOld).toFixed(2)}
                    </span>
                  )
                  },
                  {
                    label: '合计',
                    prop: 'averageTimeSpanTotal',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>
                      {row.answerCountTotal > 0 &&
                        (row.answerTimeSpanTotal / row.answerCountTotal).toFixed(2)}
                    </span>
                  )
                  }
                ]
              }
            ]
          },
          {
            label: '外拨情况统计',
            prop: 'statistics2',
            align: 'center',
            children: [
              {
                label: '总外拨',
                prop: 'callOutTotal',
                align: 'center',
                width: 100,
                render: (h, { row, $index }) => (
                <span>{this.commonFormatter(row.callOutTotal)}</span>
              )
              },
              {
                label: '销售订单数量',
                prop: 'saleCount',
                align: 'center',
                width: 120,
                children: [
                  {
                    label: '新客户',
                    prop: 'saleCountNew',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.saleCountNew)}</span>
                  )
                  },
                  {
                    label: '老客户',
                    prop: 'saleCountOld',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.saleCountOld)}</span>
                  )
                  },
                  {
                    label: '合计',
                    prop: 'saleCountTotal',
                    align: 'center',
                    width: 100,
                    render: (h, { row, $index }) => (
                    <span>{this.commonFormatter(row.saleCountTotal)}</span>
                  )
                  }
                ]
              }
            ]
          },
          {
            label: '下单类型统计',
            prop: 'statistics3',
            align: 'center',
            children: [
              {
                label: '报修单数量',
                prop: 'repairCount',
                align: 'center',
                width: 120,
                render: (h, { row, $index }) => (
                <span>{this.commonFormatter(row.repairCount)}</span>
              )
              },
              {
                label: '投诉单数量',
                prop: 'complainCount',
                align: 'center',
                width: 120,
                render: (h, { row, $index }) => (
                <span>{this.commonFormatter(row.complainCount)}</span>
              )
              },
              {
                label: '退瓶单数量',
                prop: 'backCount',
                align: 'center',
                width: 120,
                render: (h, { row, $index }) => (
                <span>{this.commonFormatter(row.backCount)}</span>
              )
              }
            ]
          }
        ]
      },
      isShowCharts() {
        const days = dayjs(this.query.date[1]).diff(dayjs(this.query.date[0]), 'days')
        return !(days > 30)
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      // 获取数据
      async getData() {
        const params = {}
        if (this.query.date && this.query.date.length > 0) {
          params[`startDt`] = dayjs(this.query.date[0]).format('YYYY-MM-DD')
          params[`endDt`] = dayjs(this.query.date[1]).format('YYYY-MM-DD')
        }
        const { status, data } = await callAnalysisNewSingleData(params)
        if (status === 200) {
          if (data.length) {
            this.tableData = data
            this.chartInit(data)
          }
        }
      },
      // 初始化chart
      chartInit(data) {
        const xAxis = []
        const averageTimeSpansNew = []
        const answerCounts = []
        const averageTimeSpansOld = []
        const title =
          this.query.date[1] - this.query.date[0] === 0
            ? `${dayjs(this.query.date[0]).format('YYYY-MM-DD')}话务数据统计`
            : `${dayjs(this.query.date[0]).format('YYYY-MM-DD')}至${dayjs(
              this.query.date[1]
            ).format('YYYY-MM-DD')}`

        data.forEach((v) => {
          xAxis.push(v.userName || '未知')
          answerCounts.push(v.answerCountTotal)

          if (v.answerCountNew > 0) {
            const averageNew = (v.answerTimeSpanNew / v.answerCountNew).toFixed(2)
            averageTimeSpansNew.push(averageNew)
          } else {
            averageTimeSpansNew.push(0)
          }

          if (v.answerCountOld > 0) {
            const averageOld = (v.answerTimeSpanOld / v.answerCountOld).toFixed(2)
            averageTimeSpansOld.push(averageOld)
          } else {
            averageTimeSpansOld.push(0)
          }
        })

        this.option = {
          title: {
            text: title,
            y: 20
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            hideDelay: 50,
            padding: 10,
            textStyle: {
              color: 'white',
              decoration: 'none',
              fontFamily: 'Verdana, sans-serif',
              fontSize: 15,
              fontStyle: 'italic'
            // fontWeight: 'bold'
            },
            formatter: function(params, ticket, callback) {
              var res = params[0].name
              for (var i = 0; i < params.length; i++) {
                res += '<br/>' + params[i].seriesName + ':' + params[i].value
              }
              setTimeout(function() {
                // 仅为了模拟异步回调
                callback(ticket, res)
              }, 0)
              return '正在加载中...'
            }
          },
          grid: {
            y: '20%',
            top: 80
          },
          legend: {
            y: 20,
            data: ['接听电话总数', '新客户平均通话时长', '老客户平均通话时长']
          },
          toolbox: {
            show: false,
            feature: {
              mark: {
                show: false
              },
              dataView: {
                show: true,
                readOnly: false
              },
              magicType: {
                show: true,
                type: ['line', 'bar']
              },
              restore: {
                show: true
              },
              saveAsImage: {
                show: true
              }
            }
          },
          xAxis: {
            splitLine: {
              show: false
            }, // 去除网格线
            data: xAxis
          },
          yAxis: [
            {
              splitLine: {
                show: false
              }, // 去除网格线
              type: 'value',
              name: '电话数量',
              nameTextStyle: {
                color: '#666666'
              },
              min: 0
            },
            {
              splitLine: {
                show: false
              }, // 去除网格线
              type: 'value',
              name: '时长/s',
              nameTextStyle: {
                color: '#666666'
              }
            }
          ],
          calculable: false,
          series: [
            {
              type: 'bar',
              barWidth: 30,
              name: '接听电话总数',
              itemStyle: {
                normal: {
                  color: '#36a9ce',
                  label: {
                    show: true,
                    textStyle: {
                      fontSize: '12'
                    }
                  }
                }
              },
              data: answerCounts,
              markPoint: {
                data: [
                  {
                    type: 'max',
                    name: '最大值'
                  },
                  {
                    type: 'min',
                    name: '最小值'
                  }
                ]
              }
            },
            {
              type: 'line',
              name: '新客户平均通话时长',
              yAxisIndex: 1,
              itemStyle: {
                normal: {
                  color: '#ff9999',
                  label: {
                    show: true,
                    textStyle: {
                      fontSize: '12',
                      color: '#ff9999'
                    },
                    formatter: function(value) {
                      return value.value + 's'
                    }
                  }
                }
              },
              data: averageTimeSpansNew
            },
            {
              type: 'line',
              name: '老客户平均通话时长',
              yAxisIndex: 1,
              itemStyle: {
                normal: {
                  color: '#ffcc99',
                  label: {
                    show: true,
                    textStyle: {
                      fontSize: '12',
                      color: '#ffcc99'
                    },
                    formatter: function(value) {
                      return value.value + 's'
                    }
                  }
                }
              },
              data: averageTimeSpansOld
            }
          ]
        }
      },

      commonFormatter(v) {
        if (v === 0) return ''
        else return v
      }
    }
  }
</script>

<style lang="scss" scoped>
.callAnalysisNew-TabSingle {
  .chart-body {
    height: 400px;
  }

  /deep/.red {
    color: #c00;
  }
}
</style>
